/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ec.edu.espe.ccsoft.mantenimiento.bean.converters;

import ec.edu.espe.ccsoft.mantenimiento.dao.MecanicoFacade;
import ec.edu.espe.ccsoft.mantenimiento.dao.TallerFacade;
import ec.edu.espe.ccsoft.mantenimiento.dao.UnidadFacade;
import ec.edu.espe.ccsoft.mantenimiento.modelos.Mecanico;
import ec.edu.espe.ccsoft.mantenimiento.modelos.Taller;
import ec.edu.espe.ccsoft.mantenimiento.modelos.Unidad;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author Carlos
 */
@FacesConverter(value = "unidadConverter", forClass = ec.edu.espe.ccsoft.mantenimiento.modelos.Unidad.class)
public class UnidadConverter implements Converter {
    
    @EJB
    private UnidadFacade unidadFacade;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        int unidadId;

        try {
            unidadId = Integer.parseInt(submittedValue);
        } catch (NumberFormatException exception) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Type the name of a Course and select it (or use the dropdown)",
                    "Type the name of a Course and select it (or use the dropdown)"));
        }

        return unidadFacade.find(unidadId);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        Unidad unidad = null;
        if (modelValue instanceof Unidad) {
            unidad = (Unidad) modelValue;
            StringBuilder asString = new StringBuilder();
            asString.append(unidad.getCodUnidad());
            return asString.toString();
        }
        return "";
    }

}
